package com.free.bsf.core.filter;

import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.core.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname CORSFilter
 * @Description
 * @Date 2021/4/13 21:28
 * @Created by chejiangyi
 */
@Slf4j
public class CORSFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        if(res.containsHeader("Access-Control-Allow-Headers"))
            return;

        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Methods", "*");
        res.addHeader("Access-Control-Allow-Headers", "*");

        if(PropertyUtils.getPropertyCache("bsf.web.cors3.cookie.enabled",false)){
            if(StringUtils.isEmpty(req.getHeader("Origin"))){
                //log.warn("bsf.web.cors2.cookie.enabled=true支持cookie传入,请求头必须传入Origin;否则以Access-Control-Allow-Origin=*进行兼容处理");
                res.addHeader("Access-Control-Allow-Origin", "*");
            }else{
                res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
            }
        }else{
            res.addHeader("Access-Control-Allow-Origin", "*");
        }

        if("OPTIONS".equals(req.getMethod().toUpperCase())){
            res.setStatus(HttpStatus.NO_CONTENT.value());
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
